package com.kaiwukj.android.ufamily.mvp.ui.page.home.message;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.haife.app.nobles.spirits.kotlin.mvp.ui.decoration.RecycleViewDivide;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.hyphenate.easeui.widget.EaseImageView;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.Constant;
import com.kaiwukj.android.ufamily.di.component.DaggerChatComponent;
import com.kaiwukj.android.ufamily.hx.DemoHelper;
import com.kaiwukj.android.ufamily.hx.UserCacheInfo;
import com.kaiwukj.android.ufamily.hx.UserCacheManager;
import com.kaiwukj.android.ufamily.mvp.contract.ChatContract;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.EMClientStateEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.CommunityGroupResult;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Copyright © KaiWu Technology Company
 *
 * @author Haife
 * @job Android Development
 * @company KW | 开物科技
 * @time 2019/7/19
 * @desc 消息列表
 */

public class ChatListFragment extends BaseMvpFragment<ChatPresenter> implements ChatContract.View, DemoHelper.OnMessageRefreshListener {
    @BindView(R.id.container_left)
    ViewGroup containerLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rv_chat_contract)
    RecyclerView mChatListRv;
    @BindView(R.id.smart_refresh_view_chat)
    SmartRefreshLayout smart_refresh_view_chat;
    private RecyclerView mGroupRv;
    private final static int MSG_REFRESH = 2;
    // private List<EMConversation> conversationList = new ArrayList<>();
    private List<CommunityGroupResult> conversationGroupList = new ArrayList<>();
    private boolean isConflict;
    private ChatListAdapter mChatAdapter;
    private List<EMConversation> groupConversationList;
    protected boolean hidden;
    private View headView;
    private GroupAdapter mGroupAdapter;

    private boolean hasRefresh = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStateEvent(EMClientStateEvent event) {
        switch (event.getState()) {
            case EMClientStateEvent.Disconnected:
                onConnectionDisconnected();
                break;
            case EMClientStateEvent.Connected:
                onConnectionConnected();
                break;
            case EMClientStateEvent.MSG_REFRESH:
                //hasRefresh = true;
//                    List<EMConversation> list = loadConversationList();
//                    for (int i = 0; i < list.size(); i++) {
//                        if (!list.get(i).isGroup()) {
//                            conversationList.add(list.get(i));
//                        }
//                    }

                mChatAdapter.setList(loadConversationList());
                break;
        }
    }

    public static ChatListFragment newInstance() {
        Bundle args = new Bundle();
        ChatListFragment fragment = new ChatListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerChatComponent
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chat;
    }

    @Override
    protected void initView() {
        //setPaddingTop(R.id.container_header);
        containerLeft.setVisibility(View.GONE);
        tvTitle.setText("消息");
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        DemoHelper.getInstance().setOnMessageRefreshListener(this);

        mChatAdapter = new ChatListAdapter();
        mGroupAdapter = new GroupAdapter(R.layout.ease_row_chat_history, conversationGroupList);

        mChatListRv.setLayoutManager(new LinearLayoutManager(getContext()));
        mChatListRv.addItemDecoration(new RecycleViewDivide(LinearLayoutManager.VERTICAL,
                null, 2,
                ContextCompat.getColor(getContext(), R.color.window_background_color)));
        mChatListRv.setAdapter(mChatAdapter);
        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.empty_view_common_container, null);
        ImageView iv = emptyView.findViewById(R.id.iv_empty_view_type);
        iv.setImageResource(R.mipmap.icon_empty_view_message);
//        无论怎样都有小区群聊所以不需要emptyView
//        mChatAdapter.setEmptyView(emptyView);
        EMClient.getInstance().addConnectionListener(connectionListener);

        // mChatAdapter.setHeaderAndEmpty(true);
        mChatAdapter.setHeaderWithEmptyEnable(true);
        headView = LayoutInflater.from(getContext()).inflate(R.layout.header_group_list_container, null);
        mGroupRv = headView.findViewById(R.id.rv_group_list);
        mGroupRv.addItemDecoration(new RecycleViewDivide(LinearLayoutManager.VERTICAL, null, 2, ContextCompat.getColor(getCtx(), R.color.window_background_color)));
        mGroupRv.setLayoutManager(new LinearLayoutManager(getContext()));
        mGroupRv.setAdapter(mGroupAdapter);
        //mChatAdapter.setHeaderView(headView);

        //refresh();
        smart_refresh_view_chat.autoRefresh();

        //刷新回调
        smart_refresh_view_chat.setOnRefreshListener(refreshLayout -> {
            refresh();
            smart_refresh_view_chat.finishRefresh();
        });

        mGroupAdapter.setOnItemClickListener((adapter, view, position) -> {
            /*if (!EMClient.getInstance().isConnected()) {
                showMessage("未连接到聊天服务器");
                return;
            }*/
            if (StringUtils.isEmpty(conversationGroupList.get(position).getGroupId())) {
                showMessage("您暂未加入该群聊");
                return;
            }
            Intent intent = new Intent(getActivity(), ChatActivity.class);
            intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
            intent.putExtra(Constant.EXTRA_GROUP_TYPE, conversationGroupList.get(position).getType());
            intent.putExtra(Constant.EXTRA_USER_ID, conversationGroupList.get(position).getGroupId());
            intent.putExtra(Constant.EXTRA_USER_NAME, conversationGroupList.get(position).getGroupName());
            startActivity(intent);
        });

        mChatAdapter.setOnItemClickListener((adapter, view1, position) -> {
            EMConversation conversation = mChatAdapter.getItem(position);
            String username = conversation.conversationId();
            UserCacheInfo info = UserCacheManager.get(username);
            if (!EMClient.getInstance().isConnected()) {
                showMessage("未连接到聊天服务器");
            } else if (username.equals(EMClient.getInstance().getCurrentUser()))
                Toast.makeText(getActivity(), R.string.Cant_chat_with_yourself, Toast.LENGTH_SHORT).show();
            else {
                // start chat acitivity
                Intent intent = new Intent(getActivity(), ChatActivity.class);
                if (conversation.isGroup()) {
                    if (conversation.getType() == EMConversation.EMConversationType.ChatRoom) {
                        // it's group chat
                        intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_CHATROOM);
                    } else {
                        intent.putExtra(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                    }
                }
                // it's single chat
                intent.putExtra(Constant.EXTRA_USER_ID, username);
                if (info != null) {
                    intent.putExtra(Constant.EXTRA_USER_NAME, info.getNickName());
                }
                startActivity(intent);
            }
        });
    }

    //    加载群聊未读消息提示
    private void refreshUnreadGroup() {
        for (EMConversation groupConversation : groupConversationList) {
            if (groupConversation.getUnreadMsgCount() > 0) {
                for (CommunityGroupResult communityGroupResult : conversationGroupList) {
                    if (communityGroupResult.getGroupId().equals(groupConversation.conversationId())) {
                        communityGroupResult.setUnReadNum(groupConversation.getUnreadMsgCount());
                        communityGroupResult.setLastMessage(groupConversation.getLastMessage());
                    }
                }
            } else {
                for (CommunityGroupResult communityGroupResult : conversationGroupList) {
                    if (communityGroupResult.getGroupId().equals(groupConversation.conversationId())) {
                        communityGroupResult.setLastMessage(groupConversation.getLastMessage());
                    }
                }
            }
        }
        mGroupAdapter.notifyDataSetChanged();
    }


    /**
     * refresh ui
     */
    private void refresh() {
        assert mPresenter != null;
        // mPresenter.requestGroupList();

        /*if (!handler.hasMessages(MSG_REFRESH)) {
            handler.sendEmptyMessage(MSG_REFRESH);
        }*/
        //   if (!hasRefresh) {
        EventBus.getDefault().post(new EMClientStateEvent(EMClientStateEvent.MSG_REFRESH));
        // }
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        super.onActivityCreated(savedInstanceState);
    }


    /**
     * load conversation list
     *
     * @return +
     */
    private List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<>();
        /**
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        groupConversationList = new ArrayList<>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            if (!sortItem.second.isGroup()) {
                list.add(sortItem.second);
            } else {
                groupConversationList.add(sortItem.second);
            }
        }
        refreshUnreadGroup();
        return list;
    }


    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, (con1, con2) -> {

            if (con1.first.equals(con2.first)) {
                return 0;
            } else if (con2.first.longValue() > con1.first.longValue()) {
                return 1;
            } else {
                return -1;
            }
        });
    }

    private EMConnectionListener connectionListener = new EMConnectionListener() {

        @Override
        public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE || error == EMError.SERVER_SERVICE_RESTRICTED
                    || error == EMError.USER_KICKED_BY_CHANGE_PASSWORD || error == EMError.USER_KICKED_BY_OTHER_DEVICE) {
                isConflict = true;
            } else {
                //handler.sendEmptyMessage(0);
                EventBus.getDefault().post(new EMClientStateEvent(EMClientStateEvent.Disconnected));
            }
        }

        @Override
        public void onConnected() {
            //handler.sendEmptyMessage(1);
            EventBus.getDefault().post(new EMClientStateEvent(EMClientStateEvent.Connected));
        }

    };

   /* @Override
    public void onSupportVisible() {
        refresh();
    }*/

    @Override
    public void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(connectionListener);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (isConflict) {
            outState.putBoolean("isConflict", true);
        }
    }

    /**
     * connected to server
     */
    protected void onConnectionConnected() {
        //errorItemContainer.setVisibility(View.GONE);
        LogUtils.d("聊天服务器已连接");
    }

    /**
     * disconnected with server
     */
    protected void onConnectionDisconnected() {
        //errorItemContainer.setVisibility(View.VISIBLE);
        LogUtils.d("聊天服务器已断开");
    }


    @Override
    public void post(Runnable runnable) {

    }

    @Override
    public void onMessageRefreshListener() {
        //refresh();
        smart_refresh_view_chat.autoRefresh();
    }

    @Override
    public Context getCtx() {
        return getContext();
    }

    @Override
    public void onGetNoticeList(List<CommunityGroupResult> list) {
        //获取联系人个数
        conversationGroupList.clear();
        conversationGroupList.addAll(list);
        //conversationList.clear();
        //  conversationList.addAll(loadConversationList());
        mChatAdapter.setList(loadConversationList());
        //群适配器
        for (int i = 0; i < conversationGroupList.size(); i++) {
            mGroupAdapter.notifyDataSetChanged();
        }
    }

    class GroupAdapter extends BaseQuickAdapter<CommunityGroupResult, BaseViewHolder> {
        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param layoutResId The layout resource id of each item.
         * @param data        A new list is created out of this one to avoid mutable list
         */
        public GroupAdapter(int layoutResId, @Nullable List<CommunityGroupResult> data) {
            super(layoutResId, data);
        }

        /**
         * Implement this method and use the helper to adapt the view to the given item.
         *
         * @param helper A fully initialized helper.
         * @param item   The item that needs to be displayed.
         */
        @Override
        protected void convert(BaseViewHolder helper, CommunityGroupResult item) {
            TextView name = helper.getView(R.id.name);
            EaseImageView avatar = helper.getView(R.id.avatar);
            Glide.with(getCtx()).load(ContextCompat.getDrawable(getCtx(), R.mipmap.linli_group_avatate)).into(avatar);
            TextView unreadLabel = helper.getView(R.id.unread_msg_number);
            if (item.getUnReadNum() > 0) {
                unreadLabel.setVisibility(View.VISIBLE);
                unreadLabel.setText(item.getUnReadNum() + "");
            } else {
                unreadLabel.setVisibility(View.GONE);
            }
            TextView message = helper.getView(R.id.message);
            TextView time = helper.getView(R.id.time);
            ImageView msg_state = helper.getView(R.id.msg_state);
            if (item.getLastMessage() != null) {
                message.setText(EaseSmileUtils.getSmiledText(getActivity(), EaseCommonUtils.getMessageDigest(item.getLastMessage(), (getActivity()))),
                        TextView.BufferType.SPANNABLE);
            }
            name.setText(item.getGroupName());
        }
    }
}
